from datetime import datetime

def generate_html_report(results, report_dir="reports"):
    """
    Generates an HTML report from test results.
    """
    failed_count = len(results.get('failed', []))
    passed_count = len(results.get('passed', []))
    total_count = failed_count + passed_count
    success_rate = (passed_count / total_count * 100) if total_count > 0 else 0
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Report</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        h1 {{ color: #333; }}
        .summary {{ background-color: #f2f2f2; padding: 15px; border-radius: 5px; margin-bottom: 20px; }}
        .summary p {{ margin: 5px 0; }}
        .results table {{ width: 100%; border-collapse: collapse; }}
        .results th, .results td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        .results th {{ background-color: #4CAF50; color: white; }}
        .status-passed {{ color: green; font-weight: bold; }}
        .status-failed {{ color: red; font-weight: bold; }}
    </style>
</head>
<body>
    <h1>Test Execution Report</h1>
    <div class="summary">
        <p><b>Report Time:</b> {timestamp}</p>
        <p><b>Total Tests:</b> {total_count}</p>
        <p><b class="status-passed">Passed:</b> {passed_count}</p>
        <p><b class="status-failed">Failed:</b> {failed_count}</p>
        <p><b>Success Rate:</b> {success_rate:.2f}%</p>
    </div>
    <div class="results">
        <h2>Detailed Results</h2>
        <table>
            <tr>
                <th>Case ID</th>
                <th>Status</th>
            </tr>
    """

    for case_id in results.get('passed', []):
        html_content += f"""
            <tr>
                <td>{case_id}</td>
                <td class="status-passed">PASSED</td>
            </tr>
        """
    
    for case_id in results.get('failed', []):
        html_content += f"""
            <tr>
                <td>{case_id}</td>
                <td class="status-failed">FAILED</td>
            </tr>
        """

    html_content += """
        </table>
    </div>
</body>
</html>
    """
    
    report_file_path = f"{report_dir}/test_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    with open(report_file_path, "w", encoding="utf-8") as f:
        f.write(html_content)
        
    return report_file_path 